package com.lianjia.analysis.service.impl;

import com.lianjia.analysis.model.HouseInfo;
import com.lianjia.analysis.model.dto.*;
import com.lianjia.analysis.repository.HouseInfoRepository;
import com.lianjia.analysis.service.AnalysisService;
import com.lianjia.analysis.service.cache.CacheService;
import com.lianjia.analysis.util.AnalysisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分析服务实现类
 */
@Service
public class AnalysisServiceImpl implements AnalysisService {

    private static final Logger logger = LoggerFactory.getLogger(AnalysisServiceImpl.class);
    private static final SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
    
    @Autowired
    private HouseInfoRepository houseInfoRepository;
    
    @Autowired
    private CacheService cacheService;

    @Override
    public SystemStatisticsDTO getSystemStatistics() {
        String cacheKey = "analysis:system_statistics";
        SystemStatisticsDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        SystemStatisticsDTO result = new SystemStatisticsDTO();
        result.setCityCount(houseInfoRepository.findDistinctCities().size());
        result.setHouseCount(houseInfoRepository.count());
        result.setAveragePrice(houseInfoRepository.findAverageUnitPrice());
        result.setMaxPrice(houseInfoRepository.findMaxUnitPrice());
        result.setMinPrice(houseInfoRepository.findMinUnitPrice());
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public List<HotCityDTO> getHotCityStatistics() {
        String cacheKey = "analysis:hot_cities";
        List<HotCityDTO> cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        List<HotCityDTO> result = houseInfoRepository.findHotCities();
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public CityStatisticsDTO getCityStatistics(String city) {
        String cacheKey = "analysis:city_statistics:" + city;
        CityStatisticsDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        CityStatisticsDTO result = new CityStatisticsDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        result.setHouseCount(cityHouses.size());
        
        // 计算平均价格
        double totalPrice = cityHouses.stream()
                .mapToDouble(HouseInfo::getUnitPrice)
                .sum();
        result.setAveragePrice(totalPrice / cityHouses.size());
        
        // 计算最高价格
        result.setMaxPrice(cityHouses.stream()
                .mapToDouble(HouseInfo::getUnitPrice)
                .max()
                .orElse(0));
        
        // 计算最低价格
        result.setMinPrice(cityHouses.stream()
                .mapToDouble(HouseInfo::getUnitPrice)
                .min()
                .orElse(0));
        
        // 计算区域统计
        Map<String, List<HouseInfo>> districtMap = cityHouses.stream()
                .collect(Collectors.groupingBy(HouseInfo::getDistrict));
        
        List<DistrictStatisticsDTO> districtStats = new ArrayList<>();
        districtMap.forEach((district, houses) -> {
            DistrictStatisticsDTO districtStat = new DistrictStatisticsDTO();
            districtStat.setDistrict(district);
            districtStat.setHouseCount(houses.size());
            
            double districtTotalPrice = houses.stream()
                    .mapToDouble(HouseInfo::getUnitPrice)
                    .sum();
            districtStat.setAveragePrice(districtTotalPrice / houses.size());
            
            districtStats.add(districtStat);
        });
        
        result.setDistrictStatistics(districtStats);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public PriceDistributionDTO getPriceDistribution(String city) {
        String cacheKey = "analysis:price_distribution:" + city;
        PriceDistributionDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        PriceDistributionDTO result = new PriceDistributionDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        // 定义价格区间
        double[] priceRanges = {0, 10000, 20000, 30000, 40000, 50000, 60000, 80000, 100000, Double.MAX_VALUE};
        String[] priceLabels = {"<1万", "1-2万", "2-3万", "3-4万", "4-5万", "5-6万", "6-8万", "8-10万", ">10万"};
        
        int[] counts = new int[priceLabels.length];
        
        // 统计每个价格区间的房源数量
        cityHouses.forEach(house -> {
            double price = house.getUnitPrice();
            for (int i = 0; i < priceRanges.length - 1; i++) {
                if (price >= priceRanges[i] && price < priceRanges[i + 1]) {
                    counts[i]++;
                    break;
                }
            }
        });
        
        result.setLabels(priceLabels);
        result.setCounts(counts);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public AreaDistributionDTO getAreaDistribution(String city) {
        String cacheKey = "analysis:area_distribution:" + city;
        AreaDistributionDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        AreaDistributionDTO result = new AreaDistributionDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        // 定义面积区间
        double[] areaRanges = {0, 50, 70, 90, 110, 130, 150, 200, Double.MAX_VALUE};
        String[] areaLabels = {"<50㎡", "50-70㎡", "70-90㎡", "90-110㎡", "110-130㎡", "130-150㎡", "150-200㎡", ">200㎡"};
        
        int[] counts = new int[areaLabels.length];
        
        // 统计每个面积区间的房源数量
        cityHouses.forEach(house -> {
            double area = house.getArea();
            for (int i = 0; i < areaRanges.length - 1; i++) {
                if (area >= areaRanges[i] && area < areaRanges[i + 1]) {
                    counts[i]++;
                    break;
                }
            }
        });
        
        result.setLabels(areaLabels);
        result.setCounts(counts);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public LayoutDistributionDTO getLayoutDistribution(String city) {
        String cacheKey = "analysis:layout_distribution:" + city;
        LayoutDistributionDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        LayoutDistributionDTO result = new LayoutDistributionDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        // 统计每种户型的房源数量和平均价格
        Map<String, List<HouseInfo>> layoutMap = cityHouses.stream()
                .filter(house -> house.getLayout() != null && !house.getLayout().isEmpty())
                .collect(Collectors.groupingBy(HouseInfo::getLayout));
        
        List<String> layouts = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        List<Double> averagePrices = new ArrayList<>();
        
        layoutMap.forEach((layout, houses) -> {
            layouts.add(layout);
            counts.add(houses.size());
            
            double totalPrice = houses.stream()
                    .mapToDouble(HouseInfo::getUnitPrice)
                    .sum();
            averagePrices.add(totalPrice / houses.size());
        });
        
        result.setLayouts(layouts);
        result.setCounts(counts);
        result.setAveragePrices(averagePrices);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public DecorationDistributionDTO getDecorationDistribution(String city) {
        String cacheKey = "analysis:decoration_distribution:" + city;
        DecorationDistributionDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        DecorationDistributionDTO result = new DecorationDistributionDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        // 统计每种装修类型的房源数量和平均价格
        Map<String, List<HouseInfo>> decorationMap = cityHouses.stream()
                .filter(house -> house.getDecoration() != null && !house.getDecoration().isEmpty())
                .collect(Collectors.groupingBy(HouseInfo::getDecoration));
        
        List<String> decorations = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        List<Double> averagePrices = new ArrayList<>();
        
        decorationMap.forEach((decoration, houses) -> {
            decorations.add(decoration);
            counts.add(houses.size());
            
            double totalPrice = houses.stream()
                    .mapToDouble(HouseInfo::getUnitPrice)
                    .sum();
            averagePrices.add(totalPrice / houses.size());
        });
        
        result.setDecorations(decorations);
        result.setCounts(counts);
        result.setAveragePrices(averagePrices);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public PriceAreaScatterDTO getPriceAreaScatter(String city) {
        String cacheKey = "analysis:price_area_scatter:" + city;
        PriceAreaScatterDTO cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        PriceAreaScatterDTO result = new PriceAreaScatterDTO();
        result.setCity(city);
        
        List<HouseInfo> cityHouses = houseInfoRepository.findByCity(city);
        if (cityHouses.isEmpty()) {
            return result;
        }
        
        // 提取面积和单价数据
        List<Double> areas = new ArrayList<>();
        List<Double> prices = new ArrayList<>();
        
        cityHouses.forEach(house -> {
            areas.add(house.getArea());
            prices.add(house.getUnitPrice());
        });
        
        result.setAreas(areas);
        result.setPrices(prices);
        
        // 计算相关系数
        result.setCorrelation(AnalysisUtils.calculateCorrelation(areas, prices));
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }

    @Override
    public List<MonthlyPriceTrendDTO> getMonthlyPriceTrend(String city) {
        String cacheKey = "analysis:monthly_price_trend:" + city;
        List<MonthlyPriceTrendDTO> cachedResult = cacheService.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 原有逻辑
        List<MonthlyPriceTrendDTO> result = houseInfoRepository.findMonthlyPriceTrend(city);
        
        // 缓存结果，1小时过期
        cacheService.set(cacheKey, result, 3600);
        return result;
    }
} 